//
//  BENetworkTools.swift
//  BEGlobalOiler
//
//  Created by KKING on 16/9/8.
//  Copyright © 2016年 Bullseye Energy pte ltd. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

/// 网络请求回调
typealias NetworkFinished = (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()

class BENetworkTools: NSObject {
    
    /// 网络工具类单例
    static let shareNetworkTool = BENetworkTools()
}

// MARK: - 基础请求方法
extension BENetworkTools {
    
    /**
     GET请求
     
     - parameter APIString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func get(APIString: String, parameters: [String : AnyObject]?, finished: @escaping NetworkFinished) {
        
        //        print("\(BASE_URL)\(APIString)")
        Alamofire.request("\(BASE_URL)\(APIString)", method: .get,parameters: parameters).responseJSON { (response) in
            
            guard response.result.isSuccess else {
                JFProgressHUD.showErrorWithStatus(status: "加载失败...")
                finished(false, nil, response.result.error as NSError?)
                return
            }
            if let value = response.result.value {
                let json = JSON(value)
                finished(true, json, nil)
            }
        }
    }
    
    /**
     带token的GET请求
     
     - parameter APIString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func getWithToken(APIString: String, parameters: [String : AnyObject]?, finished: @escaping NetworkFinished) {
        
        guard let token = BEAccountModel.shareAccount()?.authToken else {
            return
        }
        
        //        print("\(BASE_URL)\(APIString)")
        Alamofire.request("\(BASE_URL)\(APIString)", method: .get , parameters: parameters, headers: ["Authorization" : "\(token)"]).responseJSON { (response) in
            
            guard response.result.isSuccess else {
                JFProgressHUD.showErrorWithStatus(status: "加载失败...")
                finished(false, nil, response.result.error as NSError?)
                return
            }
            if let value = response.result.value {
                let json = JSON(value)
                finished(true, json, nil)
            }
        }
    }
    
    
    /**
     POST请求
     
     - parameter APIString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func post(APIString: String, parameters: [String : AnyObject]?, finished: @escaping NetworkFinished) {
        
        Alamofire.request("\(BASE_URL)\(APIString)", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { (response) in
            guard response.result.isSuccess else {
                JFProgressHUD.showErrorWithStatus(status: "加载失败...")
                finished(false, nil, response.result.error as NSError?)
                return
            }
            if let value = response.result.value {
                let json = JSON(value)
                finished(true, json, nil)
            }
        }
    }
    
    /**
     带token的POST请求
     
     - parameter APIString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func postWithToken(APIString: String, parameters: [String : AnyObject]?, finished: @escaping NetworkFinished) {
        
        guard let token = BEAccountModel.shareAccount()?.authToken else {
            return
        }
        guard let timeZone = BEAccountModel.shareAccount()?.defaultTimezoneId else {
            return
        }
        
        let headers = [
            "Authorization" : "\(token)",
            "TimeZone" : "\(timeZone)"
        ]
        
    Alamofire.request("\(BASE_URL)\(APIString)", method: .post,parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
            guard response.result.isSuccess else {
                JFProgressHUD.showErrorWithStatus(status: "加载失败...")
                finished(false, nil, response.result.error as NSError?)
                return
            }
            if let value = response.result.value {
                let json = JSON(value)
                finished(true, json, nil)
            }
        }
    }
    
    
}


// MARK: - 辅助方法
extension BENetworkTools {
    
    /**
     对象转json
     */
    func objectToJson(object: AnyObject) -> NSString? {
        do {
            let data = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted)
            return NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        } catch {
            return nil
        }
    }
    
    /**
     获取当前网络状态
     
     - returns: 0未知 1WiFi 22G 33G 44G
     */
    func getCurrentNetworkState() -> Int {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.networkState
    }
}



//登录 工单列表 工单详情 创建订单 确认订单 确认订单完成
extension BENetworkTools{
    //获得平台信息,银行卡保存到沙盒中.
    func getPlatformInfo(finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        get(APIString: GET_PLATFORM_INFO, parameters: nil, finished: finished)
    }
    
    //登录
    func normalAccountLogin(username: String, password: String, finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        var deviceToken = UserDefaults.standard.object(forKey: "deviceToken")
        
        if deviceToken == nil {
            deviceToken = NSNull.self
        }
        let parameters: [String : AnyObject] = [
            "userName" : username as AnyObject,
            "password" : password as AnyObject,
            "iosDeviceToken": NSNull()
        ]
        //        print(deviceToken!)
        post(APIString: LOGIN, parameters: parameters, finished: finished)
    }
    
    //按不同状态查询订单
    func loadOrderListData(orderStatus:Int,finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        var orderStatusIn: String = ""
        switch orderStatus {
        //待确认
        case 0:
            orderStatusIn = "0|1|2|3"
        //进行中
        case 1:
            orderStatusIn = "4|5"
        //待付款
        case 2:
            orderStatusIn = "13"
        //已完成
        case 3:
            orderStatusIn = "14"
        default:
            orderStatusIn = ""
        }
        let parameters: [String : AnyObject] = [
            "orderStatus_in" : orderStatusIn as AnyObject,
            ]
        getWithToken(APIString: GET_ORDER_LIST, parameters: parameters, finished: finished)
    }
    
    //查看订单详情
    func loadOrderDetailData(orderId:Int64,finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        let GET_ORDER_DETAIL_NEW = GET_ORDER_DETAIL + "\(orderId)"
        getWithToken(APIString: GET_ORDER_DETAIL_NEW, parameters: nil, finished: finished)
    }
    
    //创建订单
    func createNewOrder(parameters: [String: AnyObject], finished:
        @escaping
        (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        postWithToken(APIString: POST_ORDER_CREATE, parameters: parameters, finished: finished)
    }
    
    
    //确认订单
    func confirmOrder(orderId: Int64,finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        let POST_ORDER_CONFIRM_NEW = POST_ORDER_CONFIRM + "\(orderId)" + "/confirm"
        //        print(POST_ORDER_CONFIRM_NEW)
        postWithToken(APIString: POST_ORDER_CONFIRM_NEW, parameters: nil, finished: finished)
    }
    
    //确认订单完成 {orderId}/complete
    func orderComplete(orderId: Int64,finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        let parameters: [String: AnyObject] = [
            "payMethod": 1 as AnyObject
        ]
        let POST_ORDER_CONPLETE_NEW = POST_ORDER_CONPLETE + "\(orderId)" + "/complete"
        postWithToken(APIString: POST_ORDER_CONPLETE_NEW, parameters: parameters, finished: finished)
    }
    
    //查看订单 工人详情页面
    func loadOrderTalentData(ordertalentId:String,finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        let GET_ORDER_TALENTINFO_NEW = GET_ORDER_TALENTINFO + ordertalentId + "/orderTalent"
//        print(GET_ORDER_TALENTINFO_NEW)
        getWithToken(APIString: GET_ORDER_TALENTINFO_NEW, parameters: nil, finished: finished)
    }
    
    //确认报告 现有的  talentid: 资源id:3814638712793464832
    func confirmPackage(ordertalentId: String,resourceId: Int64,finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        //        let parameters = ["resourceId": "\(3814638712793464832)"]
        let POST_PACKAGE_CONFIRMED_NEW = POST_PACKAGE_CONFIRMED + ordertalentId + "/packageConfirmed"
        postWithToken(APIString: POST_PACKAGE_CONFIRMED_NEW, parameters: nil, finished: finished)
    }
    
    //获取评价问题
    func loadAllGradeInfo(finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        getWithToken(APIString: GET_GREDEINFO, parameters: nil, finished: finished)
    }
    
    //提交问题评价
    func talentEvaluate(ordertalentId: String,parameters: [String: AnyObject],finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        let POST_EVALUATE_NEW = POST_EVALUATE + ordertalentId + "/evaluate"
        postWithToken(APIString:
            POST_EVALUATE_NEW, parameters: parameters, finished: finished)
    }
    
    //获取jobType
    func getJobType(finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        getWithToken(APIString: GET_JOB_TYPE, parameters: nil, finished: finished)
    }
    
    //获取当前公司的所有油井
    func getSiteBy(companyId: String,finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        let GET_SITE_BYCOMPANY_NEW = GET_SITE_BYCOMPANY + companyId
        getWithToken(APIString: GET_SITE_BYCOMPANY_NEW, parameters: nil, finished: finished)
    }
    
    //获取设备类型
    func getEquipmentType(finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        getWithToken(APIString: GET_EQUIP_ALL_TYPE, parameters: nil, finished: finished)
    }
    
    //获取设备品牌
    func getEquipmentBrand(finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        getWithToken(APIString: GET_EQUIP_ALL_BRAND, parameters: nil, finished: finished)
    }
    
    //获取品牌下的设备   -- 需要参数为设备品牌
    func getEquipModelBy(brandId: String,finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        let GET_EQUIP_MODEL_NEW = GET_EQUIP_MODEL + brandId
        getWithToken(APIString: GET_EQUIP_MODEL_NEW, parameters: nil, finished: finished)
    }
    
    //获取设备   -- 参数为设备类型id 品牌id 型号id
    func getEquipBy(companyId: String,parameters: [String: AnyObject],finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        let GET_EQUIP_EQUIP_NEW = GET_EQUIP_EQUIP + companyId
        getWithToken(APIString: GET_EQUIP_EQUIP_NEW, parameters: parameters, finished: finished)
    }
    
    //查看工人列表
    func loadTechListData(finished: @escaping (_ success: Bool, _ result: JSON?, _ error: NSError?) -> ()){
        getWithToken(APIString: GET_TECH_LIST, parameters: nil, finished: finished)
    }
    
    //查看个人详细信息
    func loadAccountInfo(finished: @escaping (_ success: Bool,_ result: JSON?,_ error: NSError?) -> ()){
        guard let peopleId = BEAccountModel.shareAccount()?.peopleId else{
            return
        }
        let GET_ACCOUNT_INFO_NEW = GET_ACCOUNT_INFO + peopleId
        getWithToken(APIString: GET_ACCOUNT_INFO_NEW, parameters: nil, finished: finished)
    }
    
    
}


